import hashlib
import pymysql
from flask import Flask, request, jsonify

app = Flask(__name__)

def fetch_one(sql, params):
    conn = pymysql.connect(host='localhost', user='root', password='12345678', db='day20')
    cursor = conn.cursor()
    cursor.execute(sql, params)
    result = cursor.fetchone()
    cursor.close()
    return result;

@app.route('/bili', methods=['POST'])
def bili():
    # 1.token是否为空
    token = request.args.get('token')
    if not token:
        return jsonify({'code': 400, 'message': 'token不能为空'})
    # 2.token是否合法，连接Mysql执行命令
    result = fetch_one('select * from user where token=%s', [token])

    if not result:
        return jsonify({'code': 400, 'message': 'token不合法'})

    ordered_string = request.json.get('ordered_string')
    if not ordered_string:
        return jsonify({'code': 400, 'message': 'ordered_string不能为空'})

    # 调用核心算法，生成sign签名
    encrypt_string = request.json.get('ordered_string') + 'ffec18f4-12e5-459c-9af5-244ef78643cc'
    obj = hashlib.md5(encrypt_string.encode('utf-8'))
    sign = obj.hexdigest()
    return {
        'code': 200,
        'data': sign,
        'name': result[2]
    }


if __name__ == '__main__':
    app.run(host='127.0.0.1', port=5000)

